<template>
  <div>
    <div style="display: flex">
      <div style="width: 640px; height: 480px">
        <video ref="video" autoplay />
      </div>
      <br />
      <canvas ref="canvas" style="display: none" />
      <hr />
      <div
        style="
          margin-right: 10px;
          float: right;
          width: 1616px;
          display: ruby;
          overflow-y: scroll;
          overflow-x: hidden;
          height: 410px;
        "
      >
        <div v-for="fit in imageSrc" :key="fit" style="margin-left: 10px">
          <!-- <span class="demonstration">{{ fit }}</span> -->
          <el-image style="width: 200px; height: 200px" :src="fit" :fit="fit" />
        </div>
      </div>
    </div>
    <br /><br />
    &nbsp;&nbsp;&nbsp;&nbsp;
    <el-button
      :disabled="imageSrc.length > 50"
      size="medium"
      style="width: 80px; height: 40px; float: left"
      type="primary"
      @click="capture"
      >采图</el-button
    >
  </div>
</template>

<script>
export default {
  props: {
    imageList: {
      default: [],
      type: Array,
    },
  },
  data() {
    return {
      imageSrc: [],
    };
  },
  watch: {
    imageList(newVal, oldVal) {
      console.log(`message changed from ${oldVal} to ${newVal}`);
      this.imageSrc = newVal;
    },
  },
  mounted() {
    this.startCamera();
  },
  beforeDestroy() {
    const stream = this.$refs.video.srcObject;
    if (stream) {
      const tracks = stream.getTracks();
      tracks.forEach((track) => track.stop());
    }
  },
  methods: {
    async startCamera() {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({
          video: true,
        });
        this.$refs.video.srcObject = stream;
      } catch (error) {
        console.error('无法访问摄像头:', error);
      }
    },
    capture() {
      const video = this.$refs.video;
      const canvas = this.$refs.canvas;
      const context = canvas.getContext('2d');

      // 设置canvas尺寸与视频一致
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;

      // 将视频画面绘制到canvas上
      context.drawImage(video, 0, 0, canvas.width, canvas.height);

      // 将canvas内容转换为图片并显示
      this.imageSrc.push(canvas.toDataURL('image/png'));
      this.$emit('image', this.imageSrc);
    },
  },
};
</script>

<style scoped>
video {
  width: 100%;
  max-width: 500px;
  height: auto;
}
</style>
